﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using System.Data;

namespace SEP.Admin
{
    public partial class ServiceReportJobEditor : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                //postback
            }
            else
            {
                //not a postback
                BindData();
            }
        }

        private void BindData()
        {
            List<State> states = new State().GetAll();
            Common.Utility.BindDropDownList<State>(ddlLocationState, states, "ABBREVIATION", "ID");
            Common.Utility.BindDropDownList<State>(ddlBillToState, states, "ABBREVIATION", "ID");

            ddlLocationState.SelectedValue = "00000000-0000-0000-0000-000000000000"; 
            ddlBillToState.SelectedValue = "00000000-0000-0000-0000-000000000000";
            
            BindSearchGridView(grvLocationSearch, Constituent.SearchAll);
                        
            string date = DateTime.Now.ToString();
            txtDate.Text = date.Substring(0, date.IndexOf(" "));

            Guid id = GetJobID();

            Job j = new Job();
            j = j.GetByID(id);

            txtDate.Text = j.UserDateAsString;
            txtJobName.Text = j.Description;

            if(j.Location != null)
            {
                if(j.Location.PrimaryContact != null)
                {
                    txtLocationContact.Text = j.Location.PrimaryContact.Name;
                }

                if(j.Location.EmailAddress != null)
                {
                    txtLocationEmail.Text = j.Location.EmailAddress.EmailAddress;            
                }

                txtLocationFacility.Text = j.Location.Name;
            
                if(j.Location.Phones != null)
                {
                    txtLocationExtension.Text = j.Location.Phone.Extension;
                    txtLocationPhone.Text = j.Location.Phone.Number;

                    try
                    {
                        txtLocationFax.Text = j.Location.Phones.First(x => x.PhoneTypeAsString.Equals("Fax")).Number;
                    } catch{}
                }

                if(j.Location.Address != null)
                {
                    txtLocationCity.Text = j.Location.Address.City;
                    txtLocationStreet.Text = j.Location.Address.AddressBlock;
                    txtLocationZip.Text = j.Location.Address.PostCode;   
                    
                    try
                    {     
                        ddlLocationState.SelectedValue = j.Location.Address.State.ID.ToString();
                    } catch{}
                }
            }

            if (j.BillTo != null)
            {
                if (j.BillTo.PrimaryContact != null)
                {
                    txtBillToContact.Text = j.BillTo.PrimaryContact.Name;
                }

                if (j.BillTo.EmailAddress != null)
                {
                    txtBillToEmail.Text = j.BillTo.EmailAddress.EmailAddress;
                }

                txtBillToFacility.Text = j.BillTo.Name;

                if (j.BillTo.Phones != null)
                {
                    txtBillToExtension.Text = j.BillTo.Phone.Extension;
                    txtBillToPhone.Text = j.BillTo.Phone.Number;

                    try
                    {
                        txtBillToFax.Text = j.BillTo.Phones.First(x => x.PhoneTypeAsString.Equals("Fax")).Number;
                    }
                    catch { }
                }

                if (j.BillTo.Address != null)
                {
                    txtBillToCity.Text = j.BillTo.Address.City;
                    txtBillToStreet.Text = j.BillTo.Address.AddressBlock;
                    txtBillToZip.Text = j.BillTo.Address.PostCode;

                    try
                    {
                        ddlBillToState.SelectedValue = j.BillTo.Address.State.ID.ToString();
                    }
                    catch { }
                }
            }
        }

        private void BindSearchGridView(GridView grv, Func<DataTable> searchAllMethod)
        {
            string searchDataTable = grv.ID + "SEARCHDATATABLE";

            DataTable dt = (DataTable)Session[searchDataTable];

            if (dt == null)
            {
                dt = searchAllMethod();
                Session[searchDataTable] = dt;
            }

            grv.DataSource = dt;
            grv.DataBind();
        }

        protected void grvLocationSearch_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            PageIndexChanging(grvLocationSearch, sender, e);
        }
        
        private void PageIndexChanging(GridView grv, object sender, GridViewPageEventArgs e)
        {
            string searchDataTableLocation = grv.ID + "SEARCHDATATABLE";
            string filteredDataTableLocation = grv.ID + "FILTEREDDATATABLE";

            DataTable dt = Session[searchDataTableLocation] as DataTable;

            if (Session[filteredDataTableLocation] != null)
            {
                dt = Session[filteredDataTableLocation] as DataTable;
            }

            grv.DataSource = dt;
            grv.PageIndex = e.NewPageIndex;
            grv.DataBind();
        }

        protected void grvLocationSearch_OnSorting(object sender, GridViewSortEventArgs e)
        {
            OnSorting(e, grvLocationSearch);
        }

        private void OnSorting(GridViewSortEventArgs e, GridView grv) 
        {
            string searchDataTableLocation = grv.ID + "SEARCHDATATABLE";
            string filteredDataTableLocation = grv.ID + "FILTEREDDATATABLE";

            DataTable dt = Session[searchDataTableLocation] as DataTable;

            if (Session[filteredDataTableLocation] != null)
            {
                dt = Session[filteredDataTableLocation] as DataTable;
            }

            if (dt != null)
            {
                //Sort the data.
                dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression, grv.ID);
                grv.DataSource = dt;
                grv.DataBind();

                Session[searchDataTableLocation] = dt;
                Session[filteredDataTableLocation] = dt;
            }            
        }

        protected void grvLocationSearch_OnRowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = 0;

            if (int.TryParse(e.CommandArgument.ToString(), out index) && !e.CommandName.Equals("Sort") && !e.CommandName.Equals("Page"))
            {
                GridViewRow selectedRow = grvLocationSearch.Rows[index];

                if (selectedRow != null)
                {
                    string val = ((HiddenField)selectedRow.FindControl("hidID")).Value;

                    if (!string.IsNullOrWhiteSpace(val))
                    {
                        Guid id = new Guid();

                        if (Guid.TryParse(val, out id))
                        {
                            string searchDataTable = grvLocationSearch.ID + "SEARCHDATATABLE";

                            DataTable dt = (DataTable)Session[searchDataTable];

                            if (dt != null)
                            {
                                foreach (DataRow row in dt.Rows)
                                {
                                    string temp = row["ID"].ToString();

                                    if (id.ToString().Equals(temp))
                                    {
                                        string name = row["NAME"].ToString();
                                        string street = row["STREET"].ToString();
                                        string city = row["CITY"].ToString();
                                        string postcode = row["POSTCODE"].ToString();
                                        string state = row["STATE"].ToString();
                                        string phone = row["PHONE"].ToString();
                                        string fax = row["FAX"].ToString();
                                        string emailaddress = row["EMAILADDRESS"].ToString();
                                        string contact = row["CONTACT"].ToString();

                                        if (e.CommandName.Equals("LOCATION"))
                                        {
                                            txtLocationFacility.Text = name;
                                            txtLocationStreet.Text = street;
                                            txtLocationCity.Text = city;
                                            txtLocationZip.Text = postcode;

                                            ListItem item = ddlLocationState.Items.FindByText(state);

                                            if (item != null)
                                            {
                                                ddlLocationState.SelectedValue = item.Value;
                                            }

                                            txtLocationPhone.Text = phone;
                                            txtLocationFax.Text = fax;
                                            txtLocationEmail.Text = emailaddress;
                                            txtLocationContact.Text = contact;
                                        }
                                        else if (e.CommandName.Equals("BILLTO"))
                                        {
                                            txtBillToFacility.Text = name;
                                            txtBillToStreet.Text = street;
                                            txtBillToCity.Text = city;
                                            txtBillToZip.Text = postcode;

                                            ListItem item = ddlBillToState.Items.FindByText(state);

                                            if (item != null)
                                            {
                                                ddlBillToState.SelectedValue = item.Value;
                                            }

                                            txtBillToPhone.Text = phone;
                                            txtBillToFax.Text = fax;
                                            txtBillToEmail.Text = emailaddress;
                                            txtBillToContact.Text = contact;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }            
        }
        
        private string GetSortDirection(string column, string gridViewName)
        {
            string sortExpressionName = gridViewName + "SortExpression";
            string sortDirectionName = gridViewName + "SortDirection";

            // By default, set the sort direction to ascending.
            string sortDirection = "ASC";

            // Retrieve the last column that was sorted.
            string sortExpression = Session[sortExpressionName] as string;

            if (sortExpression != null)
            {
                // Check if the same column is being sorted.
                // Otherwise, the default value can be returned.
                if (sortExpression == column)
                {
                    string lastDirection = Session[sortDirectionName] as string;
                    if ((lastDirection != null) && (lastDirection == "ASC"))
                    {
                        sortDirection = "DESC";
                    }
                }
            }

            // Save new values in ViewState.
            Session[sortDirectionName] = sortDirection;
            Session[sortExpressionName] = column;

            return sortDirection;
        }

        protected void btnLocationSubmit_Click(object sender, EventArgs e)
        {
            string text = txtLocationSearch.Text;
            string searchString = "Name like '%" + text + "%' or Contact like '%" + text + "%'";

            SearchGridView(grvLocationSearch, searchString);
        }

        private void SearchGridView(GridView grv, string searchCriteria)
        {
            string searchDataTable = grv.ID + "SEARCHDATATABLE";

            if (!string.IsNullOrWhiteSpace(searchCriteria))
            {
                string filteredDataTable = grv.ID + "FILTEREDDATATABLE";

                DataTable dt = Session[searchDataTable] as DataTable;

                if (dt != null)
                {
                    DataRow[] rows = dt.Select(searchCriteria);
                    DataTable filtered = dt.Copy();

                    filtered.Rows.Clear();

                    foreach (DataRow r in rows)
                    {
                        filtered.ImportRow(r);
                    }

                    Session[filteredDataTable] = filtered;

                    grv.DataSource = filtered;
                    grv.DataBind();
                }
            }
            else
            {
                grv.DataSource = searchDataTable;
                grv.DataBind();
            }
        }
        
        protected void btnSubmit_OnClick(object sender, EventArgs e)
        {
            Job job = null;

            try
            {
                job = GetCurrentJob();
                job.Update();
            }
            catch (Exception ex)
            {
                lblError.Text = ex.Message;
                lblError.Visible = true;
            }

            if (job.ID != Guid.Empty)
            {
                //the job was created successfully now lets send to the service report bank
                Response.Redirect(string.Format("~/Admin/ServiceReportView.aspx?jobid={0}", job.ID));
            }
        }

        private Guid GetJobID()
        {
            Guid id = Guid.Empty;

            if(Request.QueryString["id"] != null)
            {
                if(!Guid.TryParse(Request.QueryString["id"].ToString(), out id))
                {
                    id = Guid.Empty;
                }
            }

            return id;
        }

        private Job GetCurrentJob()
        {
            Job job = new Job();
            job.ID = GetJobID();

            if(job.ID != Guid.Empty)
            {
                //job name
                job.Description = txtJobName.Text;

                //job date
                job.UserDate = Convert.ToDateTime(txtDate.Text);

                //start location
                Constituent location = new Constituent();
                location.Name = txtLocationFacility.Text;

                //contact
                Constituent contact = new Constituent();
                contact.Name = txtLocationContact.Text;
                location.PrimaryContact = contact;

                //state
                State s = new State();
                s.ID = new Guid(ddlLocationState.SelectedItem.Value);
                s.Abbreviation = (string.IsNullOrWhiteSpace(ddlLocationState.SelectedItem.Text) ? string.Empty : ddlLocationState.SelectedItem.Text);

                //address
                Address address = new Address();
                address.AddressBlock = txtLocationStreet.Text;
                address.City = txtLocationCity.Text;
                address.PostCode = txtLocationZip.Text;
                address.State = s;

                location.Address = address;

                //phone number
                Phone phone = new Phone();
                phone.Number = txtLocationPhone.Text;
                phone.Extension = txtLocationExtension.Text;

                location.Phone = phone;

                //fax            
                phone = new Phone();
                phone.Number = txtLocationFax.Text;

                PhoneType phoneType = new PhoneType();
                phoneType.Description = "Fax";

                phone.PhoneType = phoneType;
                location.Phones.Add(phone);

                //email            
                Email email = new Email();
                email.EmailAddress = txtLocationEmail.Text;

                location.EmailAddress = email;

                job.Location = location;
                //end location

                //start bill to
                Constituent billto = new Constituent();

                billto.Name = txtBillToFacility.Text;

                //contact
                contact = new Constituent();
                contact.Name = txtBillToContact.Text;
                billto.PrimaryContact = contact;


                //state
                s = new State();
                s.ID = new Guid(ddlBillToState.SelectedItem.Value);
                s.Abbreviation = (string.IsNullOrWhiteSpace(ddlBillToState.SelectedItem.Text) ? string.Empty : ddlBillToState.SelectedItem.Text);

                //address
                address = new Address();
                address.AddressBlock = txtBillToStreet.Text;
                address.City = txtBillToCity.Text;
                address.PostCode = txtBillToZip.Text;
                address.State = s;

                billto.Address = address;

                //phone number
                phone = new Phone();
                phone.Number = txtBillToPhone.Text;
                phone.Extension = txtBillToExtension.Text;

                billto.Phone = phone;

                //fax            
                phone = new Phone();
                phone.Number = txtBillToFax.Text;
                phone.PhoneType = phoneType;
                billto.Phones.Add(phone);

                //email            
                email = new Email();
                email.EmailAddress = txtBillToEmail.Text;

                billto.EmailAddress = email;

                job.BillTo = billto;
                //end bill to
            }
            else
            {
                job = null;
            }

            return job;
        }

        protected void btnLocationReset_Click(object sender, EventArgs e)
        {
            SearchGridView(grvLocationSearch, string.Empty);
        }
    }
}